using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;


namespace Nop.Web.Services.Easemob
{
    internal class TokenProvider
    {
        private EasemobManager mEasemobManager;

        private string mAccessToken = string.Empty;

        private DateTime mExpiresTime;

        private object mGetLocker = new object();

        public TokenProvider(EasemobManager easemobManager)
        {
            mEasemobManager = easemobManager;
            mExpiresTime = DateTime.MinValue;
            LoadCache();
        }



        public string GetToken()
        {
            if (DateTime.Now >= mExpiresTime)
            {
                lock (mGetLocker)
                {
                    if (DateTime.Now >= mExpiresTime)
                    {
                        string text = string.Format(mEasemobManager.UrlBase + "token", mEasemobManager.OrgName, mEasemobManager.AppName);
                        Dictionary<string, string> dictionary = new Dictionary<string, string>();
                        dictionary.Add("Content-Type", "application/json");
                        string text2 = "{\"grant_type\":\"client_credentials\",\"client_id\":\"" + mEasemobManager.ClientID + "\",\"client_secret\":\"" + mEasemobManager.ClientSecret + "\"}";
                        var json = HttpEx.SyncPost(text, text2, Encoding.UTF8, dictionary);
                        SetFromJson(json);
                        SetCache(json);
                    }
                }
            }
            return mAccessToken;
        }

        private void SetCache(string json)
        {
            try
            {
                File.WriteAllText(".Easemob_Token", json, Encoding.UTF8);
            }
            catch (Exception ex)
            {


            }
        }

        private void LoadCache()
        {
            try
            {
                var json = File.ReadAllText(".Easemob_Token", Encoding.UTF8);
                if (!string.IsNullOrEmpty(json))
                {
                    SetFromJson(json);
                }
            }
            catch (Exception ex)
            {


            }

        }

        private void SetFromJson(string json)
        {

            Dictionary<string, object> dictionary2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
            if (!dictionary2.ContainsKey("access_token") || !dictionary2.ContainsKey("expires_in"))
            {
                throw new Exception("easemob access token get error");
            }
            mAccessToken = dictionary2["access_token"].ToString();
            int num = TypeConverter.ObjectToInt(dictionary2["expires_in"], 5184000);
            mExpiresTime = DateTime.Now.AddSeconds(num);
        }
    }
}
